package mall.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import mall.pojo.Industry;
import mall.pojo.Member;
import mall.pojo.Shop;
import mall.service.IndustryService;
import mall.service.MemberService;
import mall.service.ShopService;
import mall.util.UtilityClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes("shopId")
public class ShopController /* implements HandlerExceptionResolver */{

	@Autowired
	private ShopService shopService;
	@Autowired
	private IndustryService industryService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ServletContext servletContext;

	@RequestMapping(value = "/listshop", method = RequestMethod.GET)
	public String listShop(Map<String, Object> map,
			@RequestParam("id") int industryId) {
		List<Shop> listShop = shopService.listShop(industryId);
		List<Industry> listIndustry = industryService.listIndustry();
		map.put("listShop", listShop);
		map.put("listIndustry", listIndustry);
		map.put("industryName", listIndustry.get(industryId - 1).getName());
		return UtilityClass.VIEW_MALL_LISTSHOP;
	}

	// create new shop blank object and pass to createshop.jsp
	@RequestMapping(value = "/createshop", method = RequestMethod.GET)
	public ModelAndView shop(Map<String, Object> map, HttpSession session) {
		Member member = (Member) session.getAttribute("userInfo");
		if (member == null) {
			return new ModelAndView(UtilityClass.VIEW_MALL_LOGIN,"member",new Member());
		}else{
			List<Industry> listIndustry = industryService.listIndustry();
			map.put("listIndustry", listIndustry);
			return new ModelAndView(UtilityClass.VIEW_MALL_CREATESHOP, "shop",
					new Shop());
		}

	}

	@RequestMapping(value = "/createshop", method = RequestMethod.POST)
	public String createShop(@ModelAttribute("shop") Shop shop,
			BindingResult bindingResult,HttpSession session) {
		String dirPath = "";
		String fileName="";
		if (!bindingResult.hasErrors()) {
			FileOutputStream outputStream = null;
			//filePath = servletContext.getRealPath("/")+"resources\\data\\";
			dirPath = servletContext.getInitParameter("directory-path");
			fileName=UtilityClass.generateUniqueFileName()+ shop.getFile().getOriginalFilename();
			try {
				outputStream = new FileOutputStream(new File(dirPath+fileName));
				outputStream.write(shop.getFile().getFileItem().get());
				outputStream.close();
			} catch (Exception e) {
				System.out.println("Error while saving file");
				return UtilityClass.VIEW_MALL_CREATESHOP; // return create shop
															// and display error
			}
		}
		shop.setDate(new Date());
		shop.setState(1); // hard code ,1 :open , 2 :closed
		Member member = (Member) session.getAttribute("userInfo");
		//Member member= new Member(null, null, null, "", "", "", "");
		//int memberId = member.getId(); 			
		shop.setPicture(servletContext.getInitParameter("uploaded-file")+fileName);
		//member.setShop(shop);
		shop.setMember(member);
		//memberService.createMember(member);
		shopService.createShop(shop);
		member.getMemberposition().setId(UtilityClass.MEMBER_POSITION_SHOP_OWNER); // change member position to shop owner
		memberService.updateMember(member);
		return UtilityClass.VIEW_MALL_INDEX; // return new shop
	}
	
	@RequestMapping(value="/manage-shop", method=RequestMethod.GET)
	public ModelAndView manageShop(@RequestParam("id") int shopId){
		ModelAndView modelAndView =new ModelAndView();
		modelAndView.addObject("shopId", shopId);
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_ADMIN);
		return modelAndView;
	}

	/*
	 * @Override public ModelAndView resolveException(HttpServletRequest arg0,
	 * HttpServletResponse arg1, Object arg2, Exception arg3) { Map<Object,
	 * Object> model = new HashMap<Object, Object>(); if (arg3 instanceof
	 * MaxUploadSizeExceededException){ model.put("errors",
	 * "File size should be less then "+
	 * ((MaxUploadSizeExceededException)arg3).getMaxUploadSize()+" byte."); }
	 * else{ model.put("errors", "Unexpected error: " + arg3.getMessage());
	 * System.out.println(arg3.getMessage()); } model.put("shop", new Shop());
	 * List<Industry> listIndustry = industryService.listIndustry();
	 * model.put("listIndustry", listIndustry); return new
	 * ModelAndView("createshop", (Map) model); //return createshop and display
	 * error }
	 */

}
